# -*- coding: utf-8 -*-
# @Time    : 2019/3/2 9:43
# @Author  : shaoeric
# @Email   : shaoeric@foxmail.com

import cv2
import os
import numpy as np
from Metric import Accuracy
import matplotlib.pyplot as plt

def get_detected_image(file, h_low, h_up, s_low, s_up, v_low, v_up, train=True):
    if train:
        path = 'train'
    else:
        path = 'test'

    # 读取原图片和检测图
    img = cv2.imread('{}/origin/{}'.format(path, file))
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)  # 注意：这里是BRG2HSV。这个坑，刚开始写成RGB2HSV，导致后续h阈值选择出错

    ground = cv2.imread('{}/ground/{}'.format(path, file.replace('.jpg', '.png').replace('.jpeg', '.png')), cv2.IMREAD_GRAYSCALE)
    h,s,v = cv2.split(img_hsv)

    img2 = np.zeros(shape=(img.shape[0], img.shape[1]))  # 实例化一个等大小的黑色图片

    img2[(v >= v_low) * (v <= v_up) * (h >= h_low) * (h <= h_up) * (s >= s_low) * (s <= s_up)] = 255  # 阈值内的改为白色255
    return img2, ground


def getACC(train=True):
    ACC = []
    FILE = []
    path = 'train'
    if not train:
        path = 'test'
    for file in os.listdir('{}/origin'.format(path)):
        img2, ground = get_detected_image(file,0, 30, 30, 220, 90, 255, train=train)
        acc = Accuracy(img2, ground).get_acc()
        ACC.append(acc)
        FILE.append(file)
    min_acc = min(ACC)
    max_acc = max(ACC)
    print(FILE[ACC.index(min_acc)], min_acc)  # yamuna_erandathi.jpg 0.22055253623188406
    print(FILE[ACC.index(max_acc)], max_acc)  # m(01-32)_gr.jpg 0.960375
    return ACC, FILE

def plot_acc(ACC, text, set='train', mode='RGB', x=5.5, y=0.8):
    plt.bar([i for i in range(len(ACC))], ACC)
    plt.title('{}-set skin detective Accuracy with {}'.format(set, mode))
    plt.xlabel('sample')
    plt.ylabel('accuracy')
    plt.text(x, y, text, fontsize=9)
    plt.show()

def main():
    # # 训练集下的RGB
    ACC, _ = getACC()
    print('average and variance of acc in train-set with HSV',
          np.average(ACC), np.var(ACC))  # 训练集下的检测准确率 0.79662207399874770.0.038813533671522814
    plot_acc(ACC, text='average acc={}\nvar of acc={}'.format(round(np.average(ACC),4), round(np.var(ACC),4)), mode='HSV', x=-1.0, y=0.92)


    # # 测试集下的RGB
    ACC, _ = getACC(train=False)
    print('average and variance of acc in test-set with HSV',
          np.average(ACC), np.var(ACC))  # 0.7959478626447057 0.04732142456418969
    plot_acc(ACC, text='average acc={}\nvar of acc={}'.format(round(np.average(ACC),4), round(np.var(ACC),4)), set='test', mode='HSV')
